import React, { Fragment, useState } from 'react';

import { Modal, Input, Form, message } from 'antd';

import LinkButton from '../../../components/LinkButton';
import { reqUpdateCategory } from '../../../api';

const { Item, useForm } = Form;

export default function ChangeCategory(props) {

    const { record, refresh } = props;
    const [visible, setVisible] = useState(false);
    const [form] = useForm();

    return (
        <Fragment>
            <LinkButton onClick={() => setVisible(visible => !visible)}>修改分类</LinkButton>
            <Modal title={setTitle(record)} visible={visible} onOk={() => change(form, record, refresh, setVisible)} onCancel={() => cancel(form, setVisible)}>
                <Form form={form}>
                    <Item
                        name="name"
                        initialValue={record.name}
                        rules={[
                            { required: true, message: '分类名不能为空', whitespace: true }
                        ]}
                    >
                        <Input placeholder="输入分类名" autoComplete="off" />
                    </Item>
                </Form>
            </Modal>
        </Fragment>
    )
}

function change(form, record, refresh, setVisible) {
    form.validateFields()
        .then(async vals => {
            const { name } = vals;
            if (name !== record.name) {
                const res = await reqUpdateCategory(record._id, name);
                if (res.status === 0) {
                    message.success('分类修改成功！');
                    setVisible(visible => !visible);
                    refresh(form.resetFields);
                } else {
                    message.error(res.msg);
                }
            } else {
                message.warn('分类名相同！');
            }
        })
        .catch(() => { })
}

function cancel(form, setVisible) {
    form.resetFields();
    setVisible(visible => !visible)
}

function setTitle(record) {
    return (
        <Fragment>
            修改分类 [<LinkButton>{record.name}</LinkButton>] 为：
        </Fragment>
    )
}